package com.furnitur.common.security;

import com.furnitur.common.util.JwtTokenUtil;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        try {
            String token = getTokenFromRequest(request);
            log.info("Processing token: {}", token);

            if (token != null && jwtTokenUtil.validateToken(token)) {
                String username = jwtTokenUtil.getUsernameFromToken(token);
                log.info("Username from token: {}", username);

                User user = userService.getUserByUsername(username);
                log.info("Found user: {}", user);

                if (user != null) {
                    // 创建一个包含用户信息的认证令牌
                    UserAuthenticationToken authentication = new UserAuthenticationToken(
                            user,
                            Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getRoleId()))
                    );

                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    log.info("Set authentication for user: {}", username);
                }
            } else {
                // 如果token无效，清除安全上下文
                SecurityContextHolder.clearContext();
                log.info("Invalid token, clearing security context");
            }

            // 继续处理链，让SecurityConfig来决定是否允许访问
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("JWT Authentication error", e);
            SecurityContextHolder.clearContext();
            chain.doFilter(request, response);
        }
    }

    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
} 